package com.xxx.common.core.config;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.sql.DataSource;

import com.xxx.common.core.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.ServletContextAware;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;


public class ApplicationConfiguer extends PropertyPlaceholderConfigurer implements ApplicationContextAware{

	private ApplicationContext applicationContext;
	
	private String querySql = "select * from app_conf where  ( profile='%s' or profile='c' ) " ;

	
	public static Properties PROPERTIES = null; 

 
	private static DruidDataSource configCenterDataSource = null;

    
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
			configCenterDataSource = new DruidDataSource();
			configCenterDataSource.setDriverClassName("com.mysql.jdbc.Driver");
			configCenterDataSource.setUrl("jdbc:mysql://nexus.heysky.com:23306/xxx?useUnicode=true&characterEncoding=utf-8");
			configCenterDataSource.setUsername("root");
			configCenterDataSource.setPassword("root");
			configCenterDataSource.setValidationQuery("select 1");
	}
	@Override
	protected Properties mergeProperties() throws IOException {
		JdbcTemplate jt = new JdbcTemplate(GetConfigCenterDataSource());

		String profile = System.getProperty("profile");

		final Properties properties = new Properties();

		if(StringUtil.isBlank(profile)){
			profile = "test";
		}
		jt.query(String.format(querySql,profile), new RowMapper<Object>() {
			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				properties.put(rs.getString("key"), rs.getString("value"));
				return null;
			}
		});

		PROPERTIES = properties;

		
		return properties; 
	}

	

	public static DruidDataSource GetConfigCenterDataSource(){
		return configCenterDataSource; 
	}
	

	 
	
}
